'use strict';

angular.module('fbdApp.templateModule')

.controller('ruleGroupCtrl', ['$scope', '$mdDialog', '$mdToast', '$filter',
  'fbdService',
  function(
    $scope, $mdDialog, $mdToast, $filter, fbdService) {

    // $scope.rules = [];

    $scope.index = ''; //选中规则在规则中的下标
    $scope.isSelected = ''; //是否有选中?
    $scope.selectedItem = {}; //选中的规则modify

    //文件上传并按照所选模板的主规则进行切割
    $scope.confirmFileUpload = function(ev) {
      console.log($scope.currentTpl, '$scope.currentTpl');
      $scope.$on('isUploaded', function(event, data) {
        if (data) {
          $mdDialog.hide();
        }
      });
      //文件上传弹框控制器
      function cfUpload($mdDialog) {
        $scope.closeDialog = function() {
          $mdDialog.cancel();
        }
      }

      $mdDialog.show({
          controller: cfUpload,
          scope: $scope,
          preserveScope: true,
          template: '<md-dialog aria-label="FileUpload dialog">' +
            '<md-dialog-content layout-padding>' +
            '<h1 class="md-display-2" >上传文件</h1>' +
            '<upload-file file-name="fileName" real-file-name="realFileName"></upload-file>' +
            '  </md-dialog-content>' +
            '  <md-dialog-actions>' +
            '    <md-button ng-click="closeDialog()" class="md-primary">' +
            '      取消' +
            '    </md-button>' +
            '  </md-dialog-actions>' +
            '</md-dialog>',
          parent: angular.element(document.body),
          targetEvent: ev,
          clickOutsideToClose: false
        })
        .then(function() {
          // $scope.waitResult = true;
          $scope.testObj = {
            type: 'file',
            content: $scope.fileName
          };
          $scope.postData = $filter('testRuleFilter')($scope.currentTpl
            .content,
            $scope.testObj);
          var promise = fbdService.testRule(
            'http://localhost:3000/api/rules/detect',
            $scope.postData);
          promise.then(function(res) {
            // $scope.waitResult = false;
            // $scope.canBeSaved = true;
            // $scope.testResult = res;
            // $scope.addData = res.rule;
            // $scope.testRuleResult = {};
            // if (res.result.length) {
            $scope.articleList = res.data;
            $scope.add();
            // }
          }, function(err) {
            // $scope.waitResult = false;
            // $scope.testResult = err;
            // $scope.testRuleResult.info = err + '，请重新发送请求';
          });
        }, function() {
          // alert('取消');
        });
    };

    $scope.select = function(item) {

      // angular.forEach($scope.rules, function(data, index) {
      //   console.log(data.name + '====')
      // });
      // alert(item);
      angular.forEach($scope.rules, function(data, index, array) {
        if (data === item) {
          // alert(index);
          $scope.index = index;
        }

      });
      $scope.isSelected = true;
      $scope.selectedItem = item;
    };

    $scope.add = function(ev) {
      if ($scope.articleList) {
        $mdDialog.show({
            controller: ruleDialogController,
            templateUrl: 'views/ruleDialog.html',
            targetEvent: ev,
            clickOutsideToClose: true,
            locals: {
              selected: {},
              articleList: angular.copy($scope.articleList)
            }
          })
          .then(function(res) {
            // console.log(res);
            $mdToast.show($mdToast.simple()
              .textContent('保存成功')
              .action('×')
              .position('bottom right')
              .hideDelay(800)
            );
            $scope.rules.push(res.addRule);
          }, function(rea) {

          });
      } else {
        $scope.confirmFileUpload();
      }
    };

    $scope.modify = function(ev) {
      // console.log($scope.selectedItem);
      $mdDialog.show({
          controller: ruleDialogController,
          templateUrl: 'views/ruleDialog.html',
          targetEvent: ev,
          clickOutsideToClose: true,
          locals: {
            selected: angular.copy($scope.selectedItem),
            articleList: angular.copy($scope.articleList)
          }
        })
        .then(function(res) {
          $scope.rules.splice($scope.index, 1, res.addRule);
          $mdToast.show($mdToast.simple()
            .textContent('修改成功')
            .action('×')
            .position('bottom right')
            .hideDelay(800)
          );
        }, function(rea) {
          // console.log($scope.selectedItem, 'select');
        });
    };

    $scope.goDel = function() {
      // alert('goDelete');
      $scope.rules.splice($scope.index, 1);
      // shareData.rules = $scope.rules;
      // console.log('shareData.rules====' + shareData.rules);
      $scope.isSelected = '';
      $scope.selectedItem = '';
      $scope.index = '';
      console.log($scope.rules);
    };

    $scope.goUp = function() {
      // alert('up');
      upAndDown(true);
      // shareData.rules = $scope.rules;
      // console.log('shareData.rules====' + shareData.rules)
    };

    $scope.goDown = function() {
      // alert('down');
      upAndDown(false);
      // shareData.rules = $scope.rules;
      // console.log('shareData.rules====' + shareData.rules);
    };

    //上移下移函数
    function upAndDown(up_or_down) {
      if (up_or_down) { //上移
        if ($scope.index === 0) {
          return;
        } else {
          var temp;
          for (var i = 1; i < $scope.rules.length; i++) {
            if ($scope.index == i) {
              temp = $scope.rules[i - 1];
              $scope.rules[i - 1] = $scope.rules[i];
              $scope.rules[i] = temp;
              $scope.index--;
              console.log($scope.rules);
              break;
            }
          }
        }
      } else { //下移

        if ($scope.index === $scope.rules.length - 1) {
          return;
        } else {
          var temp;
          for (var i = 0; i < $scope.rules.length - 1; i++) {
            if ($scope.index == i) {
              temp = $scope.rules[i + 1];
              $scope.rules[i + 1] = $scope.rules[i];
              $scope.rules[i] = temp;
              $scope.index++;
              console.log($scope.rules);
              break;
            }
          }
        }
      }

    }

    function ruleDialogController($scope, $mdDialog, $filter, fbdService,
      selected, articleList) {
      // console.log(selected);
      // $scope.ruleData用于传入add-rule中
      // $scope.ruleData = selected;
      // 转换格式显示
      $scope.articleList = articleList;
      $scope.ruleObj = selected;
      if ($scope.ruleObj.type != undefined) {
        $scope.ruleObj.type = $scope.ruleObj.type.toString();
      }


      // console.log($scope.ruleData);
      $scope.cancel = function() {
        $mdDialog.cancel();
      }

      $scope.saveRule = function() {
        $scope.testResult.rule.name = $scope.ruleObj.name;
        var res = {
          addRule: $scope.testResult.rule
        };
        $mdDialog.hide(res);
      }

      $scope.test = function() {
        // console.log($scope.selectedArticle);
        $scope.waitResult = true;
        $scope.testObj = {
          type: 'string',
          content: $scope.selectedArticle
        };
        $scope.postData = $filter('testRuleFilter')($scope.ruleObj,
          $scope.testObj);
        // $scope.testResult = {};

        var promise = fbdService.testRule(
          'http://localhost:3000/api/rules/detect',
          $scope.postData);
        promise.then(function(res) {
          $scope.waitResult = false;
          // console.log(res);
          // console.log($scope.selectedArticle);
          // console.log(res);
          $scope.canBeSaved = true;
          // $scope.addData = res.rule;
          $scope.testResult = res;

        }, function(err) {
          // console.log(err);
          $scope.waitResult = false;
          $scope.testResult = err;
        });
      };
    }
  }
]);
